<?php
	/**
	* This class handles the conversations between students and landlords.
	* Makes everything a whole lot cleaner by handling all the queries.
	*/
	class Conversation {
		// old-skool boolean logic for message attributes
		const MESSAGE_NONE 			 = 0;	// no messages
		const MESSAGE_UNREAD		 = 1;	// unread message
		const MESSAGE_READ			 = 2;	// can set message read by << 1
		const MESSAGE_DELETED		 = 4;	// can set message deleted by << 1 or << 2 from _read or _unread respectively
		
		const MESSAGE_VISIBLE 		 = 3; 	// MESSAGE_READ   | MESSAGE_UNREAD
		const MESSAGE_UNREAD_DELETED = 5; 	// MESSAGE_UNREAD | MESSAGE_DELETED
		const MESSAGE_READ_DELETED 	 = 6;	// MESSAGE_READ   | MESSAGE_DELETED
		const MESSAGE_ALL 			 = 7;	// MESSAGE_VISIBLE| MESSAGE_DELETED
		
		
		private static function encodeSubject($listingid, $sender, $recipient) {
            $primary_hash = md5($listingid  . "," . $sender  . "," . $recipient);
            $inverse_hash = md5($listingid  . "," . $recipient  . "," . $sender);
            return array($primary_hash,$inverse_hash);
		}
		
		static function CountUnreadMessages($listing = NULL, $with = NULL) {
            $me = AuthManager::GetUserID();
            $query = "SELECT * FROM conversations WHERE recipient=$me AND (attributes & 1 = 1)";
            if (!is_null($listingid))
                $query .= " AND listingid=$listing ";
            if (!is_null($with))
                $query .= " AND sender=$with";
            $query .= ";";
            return DBM::CountRows($query); 
		}
		
		// role comes into play for this function--
		// if you're a landlord, you should only get the messages for a specific student
		// if you're a student, you should get all the messages for that listing id where you're the sender or recipient
		static function GetConversationMessages($listingid, $recipient = NULL) {
            $messages = array();
            if (AuthManager::ListingBelongsTo($listingid)) {
                // landlord owns this listing
                if (is_null($recipient)) {
                    ErrorMessage::Show("Error","Recipient was NULL.  Could not get messages.");
                    return;
                }
                
                $messages = self::GetMyMessages(self::MESSAGE_VISIBLE, $listingid, $recipient);
            }
            else if (AuthManager::CheckPermissions(AuthConstants::LANDLORDS)) {
                // landlord talking to a landlord -- disallow
                ErrorMessage::Show("Error","Landlords cannot view conversations from other landlords.  Landlords also cannot communicate with other landlords via this system.");
                return;
            }
            else {
                // student - get the messages
                $messages = self::GetMyMessages(self::MESSAGE_VISIBLE, $listingid);
            }
            return $messages;
		}
		
		static function SendMessage($to, $about, $message) {
            $listing = ListingManager::FetchListing($about);
            if (is_null($listing)) {
                ErrorMessage::Show("Error","That listing doesn't exist.  You can't send messages about it.");
            }
            
            list($p_hash, $s_hash) = self::encodeSubject($about,AuthManager::GetUserID(),$to);
            
            $build = array(
                "listingid" => $about,
                "message" => mysql_real_escape_string($message),
                "date" => time(),
                "sender" => AuthManager::GetUserID(),
                "recipient" => $to,
                "attributes" => 1
            );
            
            DBM::Execute(QueryTools::CreateQuery($build, "conversations"));
            
            return true;
		}
		
		static function GetMessageList() {
            return self::GetMyMessages(self::MESSAGE_VISIBLE);
		}
		
		// him denotes the other person in the conversation
		static function GetMyMessages($attributes, $listingid = NULL, $him = NULL, $sortorder = "ASC") {
            $me = AuthManager::GetUserID();
            if (is_null($him) && !is_null($listingid) && AuthManager::ListingBelongsTo($listingid))
                return;
            else if (is_null($him) && !is_null($listingid)) {
                $listing = ListingManager::FetchListing($listingid);
                $landlord = $listing->GetLandlord(true);
                $him = $landlord;
            }
            
            $query = "SELECT * FROM conversations WHERE ";
            
            if (!is_null($listingid))
                $query .= "listingid=$listingid AND ";
                
            if (!is_null($me) && !is_null($him)) {
                $query .= "((sender=$me AND recipient=$him) OR ";
                $query .= " (sender=$him AND recipient=$me)) ";
            }
            else $query .= "(sender=$me OR recipient=$me) ";
            
            // now apply filters
            $filters = array();
            for ($x = 0; $x < 8; $x++) {
                $attribs = $attributes & $x;
                if ($attribs == $x) {
                    $filters[] = "(attributes=$x)";
                }
            }
            
            if (count ($filters) > 1) {
                $query .= "AND (";
                $query .= implode(" OR ",$filters);
                $query .= ") ";
            }
            else if (count($filters) == 1) {
                $query .= "AND $filters[0] ";
            }
            
            // sort the results
            if (!is_null($listingid))
                $query .= "ORDER BY date $sortorder;";
            else
                $query .= "ORDER BY listingid, sender, recipient, date $sortorder;";
            
            
            return DBM::FetchAllRows($query);
		}
	}
?>